package com.ledim.ledimview;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import com.ledim.bean.LedimAccountBean;
import com.ledim.bean.LoginResponseBean;
import com.ledim.bean.WeixinResponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.ledim.share.LeDimAuthListner;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import com.letv.android.young.client.R;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class OtherLoginView extends LinearLayout
        implements View.OnClickListener, IWXAPIEventHandler {

    private View mWechat;
    private View mWebo;
    private View mQq;
    private Context mContext;
    private IWXAPI mWeixinAPI;
    private Tencent mTencent;
    private AuthInfo mAuthInfo;
    private SsoHandler mSsoHandler;
    private Intent mIntent;
    private LoadingBar mLoading;

    public OtherLoginView(Context context) {
        super(context);
        mContext = context;
    }

    public OtherLoginView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public OtherLoginView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        init();
    }

    //绑定数据
    public void bindData(Intent intent) {
        this.mIntent = intent;
        //注册微信
        mWeixinAPI =
                WXAPIFactory.createWXAPI(mContext, ConstantUtil.ShareConstant.WEIXIN_APP_ID, true);
        mWeixinAPI.registerApp(ConstantUtil.ShareConstant.WEIXIN_APP_ID);
        mWeixinAPI.handleIntent(mIntent, this);
        //注册微博
        mAuthInfo =
                new AuthInfo(mContext, ConstantUtil.ShareConstant.SINA_APP_KEY, ConstantUtil.ShareConstant.SINA_REDIRECT_URL, ConstantUtil.ShareConstant.SINA_SCOPE);
        mSsoHandler = new SsoHandler((Activity) mContext, mAuthInfo);
        //注册QQ
        mTencent = Tencent.createInstance(ConstantUtil.ShareConstant.QQZone_API_ID, mContext);
    }

    /**
     * 初始化界面
     */
    private void init() {
        mWechat = findViewById(R.id.user_login_wechat);
        mWebo = findViewById(R.id.user_login_webo);
        mQq = findViewById(R.id.user_login_qq);

        mWechat.setOnClickListener(this);
        mWebo.setOnClickListener(this);
        mQq.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (!LedimNetWorkUtils.isNetworkAvailable(mContext)) {
            ToastUtil.toast(R.string.net_error);
            return;
        }
        switch (v.getId()) {
            case R.id.user_login_wechat:
                if (mWeixinAPI.isWXAppInstalled()) {
                    weixinLogin();
                } else {
                    ToastUtil.toast(R.string.not_install_weixinclient);
                }
                break;
            case R.id.user_login_webo:
                if (mSsoHandler.isWeiboAppInstalled()) {
                    mSsoHandler.authorizeClientSso(new LeDimAuthListner(mContext) {

                        @Override
                        public void onSuccess(int platform, String auth_token, String user_id) {
                            autoLogin(platform, auth_token, user_id);
                        }
                    });

                } else {
                    ToastUtil.toast(R.string.not_install_weiboclient);
                }

                break;
            case R.id.user_login_qq:
                qq_login();
                break;
        }
    }

    public void WeixinhandleIntent(Intent intent) {
        mWeixinAPI.handleIntent(intent, this);
    }

    public void activityResult(int requestCode, int resultCode, Intent data) {
        // SSO 授权回调
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    public void event(String code) {
        //微信请求数据
        weixinAccessCode(ConstantUtil.ShareConstant.WEIXIN_APP_ID, ConstantUtil.ShareConstant.WEIXIN_APP_KEY, code, "authorization_code");
    }

    /**
     * 微信登录
     */
    private void weixinLogin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "letv";
        mWeixinAPI.sendReq(req);//调用微信登录，在WXEntryActivity中onResp()返回微信登录，分享信息
    }

    /**
     * QQ登录
     */
    private void qq_login() {
        mTencent.login((Activity) mContext, "all", new IUiListener() {
            @Override
            public void onError(UiError arg0) { }

            @Override
            public void onComplete(Object response) {
                JSONObject jsonObject = (JSONObject) response;
                try {
                    String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
                    String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
                    String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
                    LedimAccountBean account = new LedimAccountBean();
                    account.auth_key = ConstantUtil.ShareConstant.QQZone_API_ID;
                    account.auth_token = token;
                    account.expires = expires;
                    account.user_id = openId;
                    account.platform = ConstantUtil.AccountType.QQ;
                    autoLogin(account.platform, account.auth_token, account.user_id);
                    //                    ToastUtil.toastShow(mContext, "QQ登录\nauth_key:" + Config.QQZone_API_ID + "\nauth_token:" + token + "\nexpires:" + expires + "\nuser_id:" + openId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancel() { }
        });
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {

    }

    /**
     * 用户第三方登录
     *
     * @param platform
     * @param auth_token
     * @param user_id
     */
    private void autoLogin(final int platform, String auth_token, String user_id) {

        if (mLoading == null) {
            mLoading = new LoadingBar((Activity) mContext);
        }
        mLoading.show();
        LedimApiServiceFactory.createService(ApiService.class)
                              .authLogin(platform, auth_token, user_id)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<LoginResponseBean>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                      mLoading.dismiss();
                                      ToastUtil.toast(e.getMessage());
                                  }

                                  @Override
                                  public void onNext(LoginResponseBean loginResponse) {
                                      super.onNext(loginResponse);
                                      mLoading.dismiss();
                                      if (loginResponse != null) {
                                          if (loginResponse.success) {

                                              LedimSpUtils.setToken(loginResponse.data.token);
                                              LedimSpUtils.setLetvId(loginResponse.ext.letvid);
                                              LedimSpUtils.setUid(loginResponse.ext.userId);
                                              LedimSpUtils.setUser(LedimGsonConverterFactory.create().gson
                                                      .toJson(loginResponse.ext));
                                              LedimSpUtils.setLogin(true);
                                              ToastUtil.toast("登录成功");
                                              if (loginResponse.ext != null &&
                                                      !TextUtils.isEmpty(loginResponse.ext.userId)) {
                                                  HashMap<String, String> params =
                                                          new HashMap<String, String>();
                                                  params.put("uid", loginResponse.ext.userId);
                                                  if (platform == ConstantUtil.AccountType.QQ) {
                                                      params.put("loginfrom", "qq");
                                                  } else if (platform ==
                                                          ConstantUtil.AccountType.WEIBO) {
                                                      params.put("loginfrom", "weibo");
                                                  } else if (platform ==
                                                          ConstantUtil.AccountType.WEIXIN) {
                                                      params.put("loginfrom", "wechat");
                                                  } else {
                                                      params.put("loginfrom", "unknow platform");
                                                  }
                                                  LeDimAnalysisUtils.reportEvent("login", params);
                                              }
                                              ((Activity) mContext).finish();
                                          } else {
                                              //登录失败
                                              ToastUtil.toast(loginResponse.message);
                                          }
                                      }
                                  }
                              });

    }

    /**
     * 微信请求
     */
    private void weixinAccessCode(String appid, String secret, String code, String grant_type) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .weixinLogin(appid, secret, code, grant_type)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new LedimHttpObserver<WeixinResponse>() {
                                  @Override
                                  public void onCompleted() {
                                      super.onCompleted();
                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      super.onError(e);
                                  }

                                  @Override
                                  public void onNext(WeixinResponse data) {
                                      super.onNext(data);
                                      if (data != null) {
                                          String token = data.access_token;
                                          String expires = String.valueOf(data.expires_in);
                                          String openId = data.openid;
                                          LedimAccountBean account = new LedimAccountBean();
                                          account.auth_key =
                                                  ConstantUtil.ShareConstant.WEIXIN_APP_ID;
                                          account.auth_token = token;
                                          account.expires = expires;
                                          account.user_id = openId;
                                          account.platform = ConstantUtil.AccountType.WEIXIN;
                                          autoLogin(account.platform, account.auth_token, account.user_id);
                                      }
                                  }
                              });
    }

}